import React, { Component } from "react";
import { Table, Space, Button } from "antd";
import TableListModal from "./components/TableListModal/TableListModal";
const data = [
  {
    key: "1",
    name: "John Brown",
    age: 9,
    address: "New York No. 1 Lake Park",
  },
  {
    key: "2",
    name: "Jim Green",
    age: 18,
    address: "London No. 1 Lake Park",
  },
  {
    key: "3",
    name: "Joe Black",
    age: 32,
    address: "Sidney No. 1 Lake Park",
  },
];

export default class TableList extends Component {
  state = {
    data,
    record: null,
  };

  columns = [
    {
      title: "Name",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "Age",
      dataIndex: "age",
      key: "age",
    },
    {
      title: "Address",
      dataIndex: "address",
      key: "address",
    },

    {
      title: "operation",
      key: "action",
      render: (record) => (
        <div>
          <Space size="middle" style={{ marginRight: "10px" }}>
            <a onClick={() => this.deleteItem(record)}>Delete</a>
          </Space>
          <Space size="middle">
            <a onClick={() => this.modifyItem(record)}>Modify</a>
          </Space>
        </div>
      ),
    },
  ];

  handleAdd = () => {
    this.modal.showModal(); //对话框
  };

  getValue = (value) => {
    const { Name, Address, Age } = value;
    const { data } = this.state; //接收子组件的值，添加进数据
    if (value.key) {
      let newData = JSON.parse(JSON.stringify(data));
      newData.splice(
        data.findIndex((i) => i.key == value.key),
        1,
        { name: Name, key: value.key, age: Age, address: Address }
      );
      this.setState({
        data: newData,
      });
    } else {
      data.push({
        //添加新信息
        key: data[data.length - 1].key + 1,
        name: Name,
        address: Address,
        age: Age,
      });
      let newData = JSON.parse(JSON.stringify(data));
      this.setState({
        data: newData,
      });
      console.log(newData);
    }
  };

  modifyItem = (record) => {
    this.modal.showModal(record);
  };

  deleteItem = (record) => {
    const { data } = this.state;
    this.setState({
      data: data.filter((item) => {
        return item.key !== record.key; //过滤删除的数据
      }),
    });
  };

  render() {
    const { data, record } = this.state;
    return (
      <div>
        <Button onClick={() => this.handleAdd()} type="primary">
          Add
        </Button>
        <Table columns={this.columns} dataSource={data} />
        <TableListModal
          ref={(e) => (this.modal = e)}
          getValue={this.getValue}
          record={record}
        />
      </div>
    );
  }
}
